import auth from "@/plugins/auth";
import router, { constantRoutes, dynamicRoutes } from "@/router";
import { getMenus } from "@/api/system/menu";
import Layout from "@/layout/index";
import ParentView from "@/components/ParentView";
import InnerLink from "@/layout/components/InnerLink";
import { deepClone } from "@/utils/index";
import useUserStore from "@/store/modules/user";
import { isMobile } from "@/utils/request";
// 匹配views里面所有的.vue文件
const modules = import.meta.glob("./../../views/**/*.vue");

const usePermissionStore = defineStore("permission", {
  state: () => ({
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: [],
    activeMenus: [],
    buttons: [],
    allBtns: [],
    menusWithButtonList: [], //自己的菜单
    selfPermissions: [],
  }),
  actions: {
    addBtnFun(list) {
      this.allBtns = [...this.allBtns, ...list];
    },
    clearBtn() {
      this.allBtns = [];
    },
    setRoutes(routes) {
      this.addRoutes = routes;
      this.routes = constantRoutes.concat(routes);
    },
    setDefaultRoutes(routes) {
      this.defaultRoutes = constantRoutes.concat(routes);
    },
    setTopbarRoutes(routes) {
      this.topbarRouters = routes;
    },
    setSidebarRouters(routes) {
      this.sidebarRouters = routes;
    },
    generateRoutes() {
      return new Promise((resolve) => {
        // 向后端请求路由数据
        getMenus().then((res) => {
          var roleList = [];

          roleList = formatMenu(res.data.Menus, true);
          this.selfPermissions = res.data.Buttons?.map((item) => item.Code);
          //是否是管理员
          if (useUserStore().userInfo?.Type == "3") {
            this.selfPermissions.push("*:*:*");
          }

          roleList.push({
            path: "/sys",
            component: "Layout",
            hidden: false,
            redirect: "noredirect",
            meta: { title: "系统管理", icon: "user" },
            children: [
              {
                path: "Menu",
                component: "system/Menu/index",
                name: "Menu",
                meta: { title: "菜单管理", icon: "menugl" },
              },
            ],
          });
          this.buttons = res.data.Buttons;
          this.activeMenus = roleList;

          this.menusWithButtonList = menusWithButton(roleList, this.buttons);
          const sdata = JSON.parse(JSON.stringify(roleList));
          const rdata = JSON.parse(JSON.stringify(roleList));
          const defaultData = JSON.parse(JSON.stringify(roleList));
          const sidebarRoutes = filterAsyncRouter(sdata);
          const rewriteRoutes = filterAsyncRouter(rdata, false, true);
          const defaultRoutes = filterAsyncRouter(defaultData);
          const asyncRoutes = filterDynamicRoutes(dynamicRoutes);
          asyncRoutes.forEach((route) => {
            router.addRoute(route);
          });
          this.setRoutes(rewriteRoutes);
          this.setSidebarRouters(constantRoutes.concat(sidebarRoutes));
          this.setDefaultRoutes(sidebarRoutes);
          this.setTopbarRoutes(defaultRoutes);
          if (isMobile) {
            resolve([]);
          } else {
            resolve(rewriteRoutes);
          }
        });
      });
    },
  },
});

function formatBtn(list, btns) {
  list?.forEach((child) => {
    btns?.map((btn) => {
      if (child.id == btn.ID_Menu) {
        if (!child.children) child.children = [];
        child.children.push({
          id: btn.ID,
          code: btn.Code,
          showAdd: true,
          ownName: btn.Name,
          menuType: "F",
          button: true,
          meta: {
            title: btn.Name,
            icon: "",
          },
        });
      }
    });
    if (child?.children?.length) {
      formatBtn(child?.children, btns);
    }
  });
}

export function menusWithButton(data, btns) {
  let list = deepClone(data) || [];
  list?.forEach((item) => {
    if (item?.children?.length) {
      formatBtn(item?.children, btns);
      // item?.children?.forEach((child) => {
      //   btns?.map((btn) => {
      //     if (child.id == btn.ID_Menu) {
      //       if (!child.children) child.children = [];
      //       child.children.push({
      //         id: btn.ID,
      //         code: btn.Code,
      //         showAdd: true,
      //         ownName: btn.Name,
      //         menuType: "F",
      //         button: true,
      //         meta: {
      //           title: btn.Name,
      //           icon: "",
      //         },
      //       });
      //     }
      //   });
      // });
    }
  });
  return list;
}

export function formatChild(data) {
  let list = data?.map((item) => {
    let obj = {
      code: item.Info.Code,
      component: item.Info.Component,
      path: item.Info.Path,
      redirect: item.Info.Redirect,
      sort: item.Info.Sort,
      hidden: false,
      id: item.Info.ID,
      pid: item.Info.Pid,
      name: item.Info.Name,
      ownName: item.Info.Name,
      menuType: "C",
      enable: item.Info.Enable,
      button: false,
      name: item.Info.Path,
      meta: {
        title: item.Info.Name,
        icon: item.Info.Icon,
        hidden: false,
        noCache: false,
        // link: item.Info.Path,
      },
    };
    if (item.Child?.length > 0) {
      console.log();
      obj.children = formatChild(item.Child);
    }
    if (item?.BindButtons) {
      usePermissionStore().addBtnFun(item.BindButtons);
    }
    // if (item.BindButtons?.length > 0) {
    //   obj.children = item.BindButtons?.map((item) => {
    //     return {
    //       code: item.Code,
    //       enable: item.Enable,
    //       menuType: "F",
    //       id: item.ID,
    //       pid: item.ID_Menu,
    //       ownName: item.Name,
    //       meta: {
    //         title: item.Name,
    //         icon: "",
    //       },
    //     };
    //   });
    // }
    return obj;
  });
  return list;
}

export function formatMenu(data) {
  usePermissionStore().clearBtn();
  let list = data?.map((item) => {
    let obj = {
      code: item.Info.Code,
      component: item.Info.Component,
      path: item.Info.Path,
      redirect: item.Info.Redirect,
      sort: item.Info.Sort,
      hidden: false,
      alwaysShow: true,
      id: item.Info.ID,
      ownName: item.Info.Name,
      pid: item.Info.Pid,
      menuType: "M",
      enable: item.Info.Enable,
      button: false,
      meta: {
        title: item.Info.Name,
        icon: item.Info.Icon,
        hidden: false,
        noCache: false,
        link: null,
      },
    };
    if (item.Child?.length > 0) {
      obj.children = formatChild(item.Child);
    }
    return obj;
  });
  return list;
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter((route) => {
    if (type && route.children) {
      route.children = filterChildren(route.children);
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === "Layout") {
        route.component = Layout;
      } else if (route.component === "ParentView") {
        route.component = ParentView;
      } else if (route.component === "InnerLink") {
        route.component = InnerLink;
      } else {
        route.component = loadView(route.component);
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type);
    } else {
      delete route["children"];
      delete route["redirect"];
    }
    return true;
  });
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = [];
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === "ParentView" && !lastRouter) {
        el.children.forEach((c) => {
          c.path = el.path + "/" + c.path;
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c));
            return;
          }
          children.push(c);
        });
        return;
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + "/" + el.path;
    }
    children = children.concat(el);
  });
  return children;
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = [];
  routes.forEach((route) => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route);
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route);
      }
    }
  });
  return res;
}

export const loadView = (view) => {
  let res;
  for (const path in modules) {
    const dir = path.split("views/")[1].split(".vue")[0];
    if (dir === view) {
      res = () => modules[path]();
    }
  }
  return res;
};

export default usePermissionStore;
